#include "MemoryObserver.h"

#include <iostream>
#include "MemoryStream.h"

namespace streamdb {

MemoryObserver::MemoryObserver() 
: NamedObserver("MemorySaver")
, stream(new MemoryStream)
, subject(new StreamProducer("memorySubject")) 
{
}

void MemoryObserver::update(const OrderedMessage & object) {
    std::cout << "MemoryObserver update:" << object.toString()  << ", will append memory" << std::endl;
    stream->append(object);
    subject->notify(object);
}

    
void MemoryObserver::attach(std::shared_ptr<StreamConsumer> & sc ){
    if(sc != nullptr){
        sc->setStream(stream);
        subject->attach(sc);
    }
}
void MemoryObserver::detach(std::shared_ptr<StreamConsumer> & sc){
    if(sc != nullptr){
        subject->detach(sc);
        sc->setStream(std::shared_ptr<SequenceStream<OrderedMessage>>(nullptr));
    }
}

void UserLogin::update(const OrderedMessage & object)  {
    if(!object.isNull()){
        if(getStream() != nullptr){
            std::cout << "UserLogin consumer:" << object.toString() << std::endl;
        }
    }
}

void NetSubject::notify(const OrderedMessage & msg) const {
    std::cout << "NetSubject: notify msg:" << msg.toString() << std::endl;
    NamedSubject::notify(msg);
}


}//namespace streamdb
